// 报表展示组件

class ReportsComponent {
    constructor() {
        this.init();
    }
    
    init() {
        // 初始化报表页面
        this.initReportsPage();
    }
    
    // 初始化报表页面
    initReportsPage() {
        // 绑定事件
        this.bindEvents();
        
        // 加载默认报表数据
        this.loadReportData();
    }
    
    bindEvents() {
        // 报表类型切换
        const reportTypeSelect = document.querySelector('#reportsPage #reportType');
        if (reportTypeSelect) {
            reportTypeSelect.addEventListener('change', (e) => this.handleReportTypeChange(e));
        }
        
        // 时间范围切换
        const timeRangeSelect = document.querySelector('#reportsPage #timeRange');
        if (timeRangeSelect) {
            timeRangeSelect.addEventListener('change', (e) => this.handleTimeRangeChange(e));
        }
        
        // 生成报表按钮
        const generateBtn = document.querySelector('#reportsPage #generateReport');
        if (generateBtn) {
            generateBtn.addEventListener('click', (e) => this.handleGenerateReport(e));
        }
    }
    
    // 处理报表类型切换
    handleReportTypeChange(e) {
        const reportType = e.target.value;
        console.log('报表类型切换到:', reportType);
        // 可以根据报表类型显示不同的选项
    }
    
    // 处理时间范围切换
    handleTimeRangeChange(e) {
        const timeRange = e.target.value;
        console.log('时间范围切换到:', timeRange);
        // 可以根据时间范围调整日期选择器
    }
    
    // 处理生成报表
    async handleGenerateReport(e) {
        e.preventDefault();
        
        const reportType = document.querySelector('#reportsPage #reportType').value;
        const timeRange = document.querySelector('#reportsPage #timeRange').value;
        const startDate = document.querySelector('#reportsPage #startDate').value;
        const endDate = document.querySelector('#reportsPage #endDate').value;
        
        try {
            const token = localStorage.getItem('authToken');
            
            // 显示加载状态
            this.setLoading(true);
            
            // 构造API请求参数
            let url = 'http://localhost:3003/api/reports';
            const params = new URLSearchParams();
            
            if (reportType) params.append('type', reportType);
            if (timeRange) params.append('range', timeRange);
            if (startDate) params.append('startDate', startDate);
            if (endDate) params.append('endDate', endDate);
            
            if (params.toString()) {
                url += '?' + params.toString();
            }
            
            // 调用后端API
            const response = await fetch(url, {
                method: 'GET',
                headers: {
                    'Authorization': `Bearer ${token}`
                }
            });
            
            const data = await response.json();
            
            if (response.ok) {
                this.renderReport(data);
            } else {
                this.showMessage(data.error || '生成报表失败', 'error');
            }
        } catch (error) {
            this.showMessage('网络错误，请稍后重试', 'error');
            console.error('Generate report error:', error);
        } finally {
            // 恢复按钮状态
            this.setLoading(false);
        }
    }
    
    // 加载报表数据
    async loadReportData() {
        try {
            const token = localStorage.getItem('authToken');
            
            // 显示加载状态
            this.showLoadingIndicator(true);
            
            // 调用后端API获取默认报表
            const response = await fetch('http://localhost:3003/api/reports?range=month', {
                method: 'GET',
                headers: {
                    'Authorization': `Bearer ${token}`
                }
            });
            
            const data = await response.json();
            
            if (response.ok) {
                this.renderReport(data);
            } else {
                this.showMessage(data.error || '加载报表失败', 'error');
            }
        } catch (error) {
            this.showMessage('网络错误，请稍后重试', 'error');
            console.error('Load report error:', error);
        } finally {
            // 隐藏加载状态
            this.showLoadingIndicator(false);
        }
    }
    
    // 渲染报表
    renderReport(reportData) {
        // 渲染图表区域
        this.renderCharts(reportData);
        
        // 渲染统计数据
        this.renderStatistics(reportData);
        
        // 渲染详细列表
        this.renderDetails(reportData);
    }
    
    // 渲染图表
    renderCharts(reportData) {
        const chartContainer = document.querySelector('#reportsPage .chart-container');
        if (!chartContainer) return;
        
        // 这里应该使用图表库（如Chart.js）来渲染图表
        // 暂时使用占位符
        chartContainer.innerHTML = `
            <div class="chart-placeholder">
                <p>收支趋势图表</p>
            </div>
            <div class="chart-placeholder">
                <p>分类支出饼图</p>
            </div>
        `;
    }
    
    // 渲染统计数据
    renderStatistics(reportData) {
        const statsContainer = document.querySelector('#reportsPage .stats-container');
        if (!statsContainer) return;
        
        // 获取统计数据
        const totalIncome = reportData.totalIncome || 0;
        const totalExpense = reportData.totalExpense || 0;
        const netIncome = totalIncome - totalExpense;
        const categoryStats = reportData.categoryStats || [];
        
        // 渲染统计数据
        statsContainer.innerHTML = `
            <div class="dashboard">
                <div class="card neon-border">
                    <h3>总收入</h3>
                    <p style="font-size: 2rem; color: #0f0;">¥${totalIncome.toFixed(2)}</p>
                </div>
                
                <div class="card neon-border">
                    <h3>总支出</h3>
                    <p style="font-size: 2rem; color: #f00;">¥${totalExpense.toFixed(2)}</p>
                </div>
                
                <div class="card neon-accent">
                    <h3>结余</h3>
                    <p style="font-size: 2rem; color: var(--accent-color);">¥${netIncome.toFixed(2)}</p>
                </div>
            </div>
        `;
    }
    
    // 渲染详细列表
    renderDetails(reportData) {
        const detailsContainer = document.querySelector('#reportsPage .details-container');
        if (!detailsContainer) return;
        
        // 获取详细数据
        const transactions = reportData.transactions || [];
        const categoryStats = reportData.categoryStats || [];
        
        // 渲染交易列表
        let transactionsHTML = '<h3>交易明细</h3>';
        if (transactions.length === 0) {
            transactionsHTML += '<p class="no-data">暂无交易数据</p>';
        } else {
            transactionsHTML += '<div class="transaction-list">';
            transactions.forEach(transaction => {
                transactionsHTML += `
                    <div class="card">
                        <div style="display: flex; justify-content: space-between; align-items: center;">
                            <div>
                                <h4>${transaction.description || (transaction.type === 'income' ? '收入' : '支出')}</h4>
                                <p>${transaction.date} | ${transaction.category_name || '未分类'}</p>
                            </div>
                            <div style="text-align: right;">
                                <p style="font-size: 1.2rem; color: ${transaction.type === 'income' ? '#0f0' : '#f00'};">
                                    ${transaction.type === 'income' ? '+' : '-'}¥${transaction.amount.toFixed(2)}
                                </p>
                            </div>
                        </div>
                    </div>
                `;
            });
            transactionsHTML += '</div>';
        }
        
        // 渲染分类统计
        let categoryStatsHTML = '<h3>分类统计</h3>';
        if (categoryStats.length === 0) {
            categoryStatsHTML += '<p class="no-data">暂无分类数据</p>';
        } else {
            categoryStatsHTML += '<div class="category-stats">';
            categoryStats.forEach(category => {
                categoryStatsHTML += `
                    <div class="card">
                        <div style="display: flex; justify-content: space-between; align-items: center;">
                            <div>
                                <h4>${category.name}</h4>
                                <p>预算: ¥${(category.budget || 0).toFixed(2)}</p>
                            </div>
                            <div style="text-align: right;">
                                <p>支出: ¥${category.amount.toFixed(2)}</p>
                                <p style="color: ${category.amount > (category.budget || 0) ? 'var(--accent-color)' : '#0f0'};">
                                    ${category.percentage.toFixed(1)}%
                                </p>
                            </div>
                        </div>
                        <div style="margin-top: 10px; height: 10px; background: rgba(255, 255, 255, 0.1); border-radius: 5px; overflow: hidden;">
                            <div style="width: ${Math.min(category.percentage, 100)}%; height: 100%; background: ${category.amount > (category.budget || 0) ? 'var(--accent-color)' : 'var(--primary-color)'};"></div>
                        </div>
                    </div>
                `;
            });
            categoryStatsHTML += '</div>';
        }
        
        detailsContainer.innerHTML = transactionsHTML + categoryStatsHTML;
    }
    
    // 设置加载状态
    setLoading(loading) {
        const generateBtn = document.querySelector('#reportsPage #generateReport');
        if (generateBtn) {
            if (loading) {
                generateBtn.disabled = true;
                generateBtn.textContent = '生成中...';
            } else {
                generateBtn.disabled = false;
                generateBtn.textContent = '生成报表';
            }
        }
    }
    
    // 显示/隐藏加载指示器
    showLoadingIndicator(show) {
        const loadingIndicator = document.querySelector('#reportsPage .loading-indicator');
        if (loadingIndicator) {
            loadingIndicator.style.display = show ? 'block' : 'none';
        }
    }
    
    // 显示消息
    showMessage(message, type) {
        // 创建消息元素
        const messageEl = document.createElement('div');
        messageEl.className = `message message-${type}`;
        messageEl.textContent = message;
        
        // 添加样式
        Object.assign(messageEl.style, {
            position: 'fixed',
            top: '20px',
            right: '20px',
            padding: '15px 20px',
            borderRadius: '5px',
            color: 'white',
            fontWeight: 'bold',
            zIndex: '1000',
            boxShadow: '0 2px 10px rgba(0,0,0,0.3)',
            transition: 'opacity 0.3s'
        });
        
        if (type === 'success') {
            messageEl.style.backgroundColor = '#4CAF50';
        } else if (type === 'info') {
            messageEl.style.backgroundColor = '#2196F3';
        } else {
            messageEl.style.backgroundColor = '#F44336';
        }
        
        // 添加到页面
        document.body.appendChild(messageEl);
        
        // 3秒后淡出并移除
        setTimeout(() => {
            messageEl.style.opacity = '0';
            setTimeout(() => {
                if (messageEl.parentNode) {
                    messageEl.parentNode.removeChild(messageEl);
                }
            }, 300);
        }, 3000);
    }
}

// 初始化报表组件
document.addEventListener('DOMContentLoaded', () => {
    window.reportsComponent = new ReportsComponent();
});